/**
 * @description works router
 */

const router = require('koa-router')()
const { splitIdAndUuid } = require('../utils/util')
const { findPublishWork, findPreviewWork } = require('../controller/works')
const { propsToStyle, getComponentsHtml } = require('../controller/render')
// const getWxConf = require('../middleware/getWxConf')
const { DEFAULT_SHARE_IMG } = require('../config/constant')

// 路由前缀
// /p/id-uuid?channel=xx
// /p/preview/id-uuid 预览不需要 channel
router.prefix('/p')

/**
 * 渲染页面
 * @param {object} ctx ctx
 * @param {object} work work 信息
 * @param {string} pageType 'publish' | 'preview'
 */
async function renderPage(ctx, work, pageType) {
  const { title, desc = '', content = {} } = work
  const { props = {}, components = [], setting = {} } = content
  const { shareImg = DEFAULT_SHARE_IMG } = setting
  // 页面样式
  const bodyStyle = propsToStyle(props)
  // 组件 html
  const componentsHtml = await getComponentsHtml(components)

  // 组件的事件
  const eventInfoList = []
  components.forEach(component => {
    // component 中事件的数据格式： { id: '', name: 'h-text', props: { actionType: "to", url: 'https://www.baidu.com' } }
    const { id, props: componentProps = {} } = component
    const { actionType, url } = componentProps
    if (actionType) {
      eventInfoList.push({ id, actionType, url })
    }
  })

  // 微信 jssdk 配置，参考 `middleware/getWxConf`
  // const { wxJsSdkMainConf = {} } = ctx
  // const mainShareConf = {
  //   title,
  //   desc,
  //   imgUrl: shareImg
  // }

  // 渲染页面
  await ctx.renderWithAssets('work', {
    title,
    desc,
    bodyStyle,
    content: componentsHtml,
    pageType,
    eventInfoList: JSON.stringify(eventInfoList) // 事件
    // wxJsSdkMainConf: JSON.stringify(wxJsSdkMainConf), // 微信 jssdk 配置
    // mainShareConf: JSON.stringify(mainShareConf) // 微信分享配置
  })
}

// router.get('/:idAndUuid', getWxConf, async ctx => {
router.get('/:idAndUuid', async ctx => {
  const { idAndUuid } = ctx.params // 10-abcd
  const { id, uuid } = splitIdAndUuid(idAndUuid)

  const work = await findPublishWork(id, uuid)
  if (work == null) {
    // 返回 404
    await ctx.renderWithAssets('404', { pageType: '404' })
    return
  }

  // 渲染页面内容
  // await ctx.render('work', {
  //   content: `<div style="color: blue;">${JSON.stringify(work)}</div>`
  // })

  if (work.isTemplate) {
    // 模板
    await renderPage(ctx, work, 'template')
  } else {
    // 正常页面
    await renderPage(ctx, work, 'publish')
  }
})

router.get('/preview/:idAndUuid', async ctx => {
  const { idAndUuid } = ctx.params
  const { id, uuid } = splitIdAndUuid(idAndUuid)

  const work = await findPreviewWork(id, uuid)
  if (work == null) {
    // 返回 404
    await ctx.renderWithAssets('404', { pageType: '404' })
    return
  }

  // // 渲染页面内容
  // await ctx.render('work', {
  //     content: `<div style="color: blue;">${JSON.stringify(work)}</div>`,
  //     pageType: 'preview',
  // })

  // 渲染页面
  await renderPage(ctx, work, 'preview')
})

module.exports = router
